/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.simin.base.easy.adapter;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.simin.base.R;
import com.simin.base.easy.EasyRecyclerView;
import com.simin.base.easy.adapter.status.DefaultEventDelegate;
import com.simin.base.easy.adapter.status.EventDelegate;
import com.simin.base.easy.adapter.status.OnLoadMoreListener;
import com.simin.base.easy.adapter.status.StateViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A concrete BaseAdapter that is backed by an array of arbitrary
 * objects.  By default this class expects that the provided resource id references
 * a single TextView.  If you want to use a more complex layout, use the constructors that
 * also takes a field id.  That field id should reference a TextView in the larger layout
 * resource.
 *
 * <p>However the TextView is referenced, it will be filled with the toString() of each object in
 * the array. You can add lists or arrays of custom objects. Override the toString() method
 * of your objects to determine what text will be displayed for the item in the list.
 *
 * <p>To use something other than TextViews for the array display, for instance, ImageViews,
 * or to have some of data besides toString() results fill the views,
 */
public class MultiTypeAdapter extends RecyclerView.Adapter<BaseViewHolder> implements IRecyclerAdapter {
    /**
     * Contains the list of objects that represent the data of this ArrayAdapter.
     * The content of this list is referred to as "the array" in the documentation.
     */
    protected List<Object> mDataList = new ArrayList<>();
    protected ArrayList<IHeaderFooterView> headers = new ArrayList<>();
    protected ArrayList<IHeaderFooterView> footers = new ArrayList<>();
    protected EventDelegate mEventDelegate = new DefaultEventDelegate(this);

    protected RecyclerView mRecyclerView;

    private LayoutInflater mLayoutInflater;

    /**
     * 数据和模板的映射表
     */
    private final Map<Object, BaseTemplate<?, BaseViewHolder<?>>> mDataTypeTemplateMap = new HashMap<>();

    /**
     * ViewType和模板的映射表
     */
    @SuppressLint("UseSparseArrays")
    private final Map<Integer, BaseTemplate<?, BaseViewHolder<?>>> mViewTypeTemplateMap = new HashMap<>();

    public class GridSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {
        protected int mMaxCount;

        public GridSpanSizeLookup(int maxCount) {
            this.mMaxCount = maxCount;
        }

        @Override
        public int getSpanSize(int position) {
            if (headers.size() != 0) {
                if (position < headers.size()) return mMaxCount;
            }
            if (footers.size() != 0) {
                int i = position - headers.size() - mDataList.size();
                if (i >= 0) {
                    return mMaxCount;
                }
            }
            return 1;
        }
    }

    public GridSpanSizeLookup obtainGridSpanSizeLookUp(int maxCount) {
        return new GridSpanSizeLookup(maxCount);
    }

    /**
     * Lock used to modify the content of {@link #mDataList}. Any write operation
     * performed on the array should be synchronized on this lock.
     */
    private final Object mLock = new Object();


    public MultiTypeAdapter(List<BaseTemplate> templateList) {
        this(templateList, new ArrayList<>());
    }

    public MultiTypeAdapter(List<BaseTemplate> templateList, List<Object> data) {
        if (data != null) {
            mDataList = data;
        }
        if (templateList == null || templateList.size() == 0) {
            return;
        }
        for (BaseTemplate template : templateList) {
            addTemplate(template);
        }
        // 容错处理，如果数据出错，使用占位的模板来显示
        if (!mViewTypeTemplateMap.containsKey(PlaceholderTemplate.sViewType)) {
            //noinspection unchecked
            addTemplate((BaseTemplate) new PlaceholderTemplate<>());
        }
    }

    /**
     * 添加模板
     *
     * @param template 被添加的模板
     */
    public void addTemplate(BaseTemplate<?, BaseViewHolder<?>> template) {
        if (template == null) {
            return;
        }
        template.mOwnerAdapter = this;
        BaseTemplate oldTemplate = mDataTypeTemplateMap.put(template.getDataType(), template);
        if (oldTemplate != null) {
            throw new IllegalArgumentException(template.getDataType() + " has multiple templates.");
        }

        final int viewType = template.getViewType();
        oldTemplate = mViewTypeTemplateMap.get(viewType);
        if (oldTemplate != null) {
            throw new IllegalArgumentException("the viewType: " + viewType + ", has already template.");
        }
        mViewTypeTemplateMap.put(viewType, template);
    }

    /**
     * 设置新的数据集合
     *
     * @param newData 新数据
     */
    public void setData(@NonNull List<?> newData) {
        if (mEventDelegate != null) {
            mEventDelegate.clear();
            mEventDelegate.addData(newData == null ? 0 : newData.size());
        }
        mDataList = (List<Object>) newData;
        notifyDataSetChanged();
    }

    public void showNoMore() {
        if (mEventDelegate == null)
            throw new NullPointerException("You should invoking setLoadMore() first");
        mEventDelegate.showNoMore();
    }

    public void errorLoadMore() {
        if (mEventDelegate == null)
            throw new NullPointerException("You should invoking setLoadMore() first");
        mEventDelegate.errorLoadMore();
    }

    public void showLoadMore() {
        if (mEventDelegate == null)
            throw new NullPointerException("You should invoking setLoadMore() first");
        mEventDelegate.showLoadMore();
    }

    public void addHeader(IHeaderFooterView view) {
        if (view == null) throw new NullPointerException("ItemView can't be null");
        headers.add(view);
        notifyItemInserted(headers.size() - 1);
    }

    public void addFooter(IHeaderFooterView view) {
        if (view == null) throw new NullPointerException("ItemView can't be null");
        footers.add(view);
        notifyItemInserted(headers.size() + getCount() + footers.size() - 1);
    }

    public void removeAllHeader() {
        int count = headers.size();
        headers.clear();
        notifyItemRangeRemoved(0, count);
    }

    public void removeAllFooter() {
        int count = footers.size();
        footers.clear();
        notifyItemRangeRemoved(headers.size() + getCount(), count);
    }

    public IHeaderFooterView getHeader(int index) {
        return headers.get(index);
    }

    public IHeaderFooterView getFooter(int index) {
        return footers.get(index);
    }

    public int getHeaderCount() {
        return headers.size();
    }

    public int getFooterCount() {
        return footers.size();
    }

    public void removeHeader(IHeaderFooterView view) {
        int position = headers.indexOf(view);
        headers.remove(view);
        notifyItemRemoved(position);
    }

    public void removeFooter(IHeaderFooterView view) {
        int position = headers.size() + getCount() + footers.indexOf(view);
        footers.remove(view);
        notifyItemRemoved(position);
    }


    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        mEventDelegate.setOnLoadMoreListener(listener);
    }

    /**
     * 设置 load more 过程中三种不同状态的 view
     *
     * @param loadingView    正在加载更多 状态
     * @param noMoreDataView 没有更多数据  状态
     * @param errorLoadView  加载数据错误  状态
     */
    public void setLoadMoreViews(View loadingView, View noMoreDataView, View errorLoadView) {
        mEventDelegate.setLoadMoreViews(loadingView, noMoreDataView, errorLoadView);
    }

    /**
     * 设置 load more 过程中三种不同状态的 view
     *
     * @param loadingView    正在加载更多 状态
     * @param noMoreDataView 没有更多数据  状态
     * @param errorLoadView  加载数据错误  状态
     */
    public void setLoadMoreViews(@LayoutRes int loadingView, @LayoutRes int noMoreDataView, @LayoutRes int errorLoadView) {
        mEventDelegate.setLoadMoreViews(createView(loadingView), createView(noMoreDataView), createView(errorLoadView));
    }

    private View createView(@LayoutRes int layoutId) {
        if(layoutId==0){
            return null;
        }
        LayoutInflater inflater = LayoutInflater.from(mRecyclerView.getContext());
        return inflater.inflate(layoutId, mRecyclerView, false);
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.mRecyclerView = recyclerView;

        //增加对RecyclerArrayAdapter奇葩操作的修复措施
        registerAdapterDataObserver(new FixDataObserver(mRecyclerView));
    }

    /**
     * 获得当前Adapter所属的RecyclerView
     *
     * @return RecyclerView对象
     */
    public RecyclerView getOwnerRecyclerView() {
        return mRecyclerView;
    }

    public boolean hasEventFooter() {
        return mEventDelegate != null;
    }

    /**
     * Adds the specified object at the end of the array.
     *
     * @param object The object to add at the end of the array.
     */
    public void add(Object object) {
        if (object == null) {
            return;
        }
        List<Object> data = new ArrayList<>(1);
        data.add(object);
        addAll(data);
    }

    /**
     * Adds the specified Collection at the end of the array.
     *
     * @param collection The Collection to add at the end of the array.
     */
    public void addAll(Collection<? extends Object> collection) {
        if (collection == null || collection.size() == 0) {
            return;
        }
        synchronized (mLock) {
            int dataCount = collection.size();
            mEventDelegate.addData(dataCount);
            mDataList.addAll(collection);
            notifyItemRangeInserted(headers.size() + getCount() - dataCount, dataCount);
            log("addAll notifyItemRangeInserted " + (headers.size() + getCount() - dataCount) + "," + (dataCount));
        }
    }

    /**
     * Adds the specified items at the end of the array.
     *
     * @param items The items to add at the end of the array.
     */
    public void addAll(Object[] items) {
        if (items == null || items.length == 0) {
            return;
        }
        addAll(Arrays.asList(items));
    }

    /**
     * 插入，不会触发任何事情
     *
     * @param object The object to insert into the array.
     * @param index  The index at which the object must be inserted.
     */
    public void insert(Object object, int index) {
        synchronized (mLock) {
            mDataList.add(index, object);
        }
        notifyItemInserted(headers.size() + index);
        log("insert notifyItemRangeInserted " + (headers.size() + index));
    }

    /**
     * 插入数组，不会触发任何事情
     *
     * @param object The object to insert into the array.
     * @param index  The index at which the object must be inserted.
     */
    public void insertAll(Object[] object, int index) {
        synchronized (mLock) {
            mDataList.addAll(index, Arrays.asList(object));
        }
        int dataCount = object == null ? 0 : object.length;
        notifyItemRangeInserted(headers.size() + index, dataCount);
        log("insertAll notifyItemRangeInserted " + ((headers.size() + index) + "," + (dataCount)));
    }

    /**
     * 插入数组，不会触发任何事情
     *
     * @param object The object to insert into the array.
     * @param index  The index at which the object must be inserted.
     */
    public void insertAll(Collection<? extends Object> object, int index) {
        synchronized (mLock) {
            mDataList.addAll(index, object);
        }
        int dataCount = object.size();
        notifyItemRangeInserted(headers.size() + index, dataCount);
        log("insertAll notifyItemRangeInserted " + ((headers.size() + index) + "," + (dataCount)));
    }


    public void update(Object object, int pos) {
        synchronized (mLock) {
            mDataList.set(pos, object);
        }
        notifyItemChanged(pos);
        log("insertAll notifyItemChanged " + pos);
    }

    /**
     * 删除，不会触发任何事情
     *
     * @param object The object to remove.
     */
    public void remove(Object object) {
        int position = mDataList.indexOf(object);
        synchronized (mLock) {
            if (mDataList.remove(object)) {
                notifyItemRemoved(headers.size() + position);
                log("remove notifyItemRemoved " + (headers.size() + position));
            }
        }
    }

    /**
     * 删除，不会触发任何事情
     *
     * @param position The position of the object to remove.
     */
    public void remove(int position) {
        synchronized (mLock) {
            mDataList.remove(position);
        }
        notifyItemRemoved(headers.size() + position);
        log("remove notifyItemRemoved " + (headers.size() + position));
    }


    /**
     * 触发清空
     * 与{@link #clear()}的不同仅在于这个使用notifyItemRangeRemoved.
     * 猜测这个方法与add伪并发执行的时候会造成"Scrapped or attached views may not be recycled"的Crash.
     * 所以建议使用{@link #clear()}
     */
    public void removeAll() {
        int count = mDataList.size();
        if (mEventDelegate != null) mEventDelegate.clear();
        synchronized (mLock) {
            mDataList.clear();
        }
        notifyItemRangeRemoved(headers.size(), count);
        log("clear notifyItemRangeRemoved " + (headers.size()) + "," + (count));
    }

    /**
     * 触发清空
     */
    public void clear() {
        int count = mDataList.size();
        if (mEventDelegate != null) mEventDelegate.clear();
        synchronized (mLock) {
            mDataList.clear();
        }
        notifyDataSetChanged();
        log("clear notifyItemRangeRemoved " + (headers.size()) + "," + (count));
    }

    /**
     * Sorts the content of this adapter using the specified comparator.
     *
     * @param comparator The comparator used to sort the objects contained
     *                   in this adapter.
     */
    public void sort(Comparator<? super Object> comparator) {
        synchronized (mLock) {
            Collections.sort(mDataList, comparator);
        }
        notifyDataSetChanged();
    }

    /**
     * 这个函数包含了头部和尾部view的个数，不是真正的item个数。
     *
     * @return
     */
    @Deprecated
    @Override
    public final int getItemCount() {
        return mDataList.size() + headers.size() + footers.size();
    }

    /**
     * 应该使用这个获取item个数
     *
     * @return
     */
    public int getCount() {
        return mDataList.size();
    }

    /**
     * header，footer
     *
     * @param parent
     * @param viewType
     * @return
     */
    private View createSpViewByType(ViewGroup parent, int viewType) {
        for (IHeaderFooterView headerView : headers) {
            if (headerView.hashCode() == viewType) {
                View view = headerView.onCreateView(parent);
                StaggeredGridLayoutManager.LayoutParams layoutParams;
                if (view.getLayoutParams() != null)
                    layoutParams = new StaggeredGridLayoutManager.LayoutParams(view.getLayoutParams());
                else
                    layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setFullSpan(true);
                view.setLayoutParams(layoutParams);
                return view;
            }
        }
        for (IHeaderFooterView footerView : footers) {
            if (footerView.hashCode() == viewType) {
                View view = footerView.onCreateView(parent);
                StaggeredGridLayoutManager.LayoutParams layoutParams;
                if (view.getLayoutParams() != null)
                    layoutParams = new StaggeredGridLayoutManager.LayoutParams(view.getLayoutParams());
                else
                    layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setFullSpan(true);
                view.setLayoutParams(layoutParams);
                return view;
            }
        }
        return null;
    }

    @Override
    public final BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = createSpViewByType(parent, viewType);
        if (view != null) {
            return new StateViewHolder(view);
        }

        if (mLayoutInflater == null) {
            mLayoutInflater = LayoutInflater.from(parent.getContext());
        }
        final BaseTemplate template = getTemplate(viewType);
        BaseViewHolder vh = template.onCreateViewHolder(mLayoutInflater, parent, viewType);
        if (vh.itemView != null) {
            vh.itemView.setTag(R.id.multi_type_adapter_view_type, Integer.valueOf(viewType));
        }

        //itemView 的点击事件
//        if (mItemClickListener != null) {
//            vh.itemView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    mItemClickListener.onItemClick(vh.getAdapterPosition() - headers.size());
//                }
//            });
//        }
//
//        if (mItemLongClickListener != null) {
//            vh.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    return mItemLongClickListener.onItemLongClick(vh.getAdapterPosition() - headers.size());
//                }
//            });
//        }
        return vh;
    }

    /**
     * 根据view类型获得模板对象
     *
     * @param viewType view类型
     * @return 模板对象
     */
    @NonNull
    private BaseTemplate<?, ?> getTemplate(int viewType) {
        return mViewTypeTemplateMap.get(viewType);
    }

    @Override
    public final void onBindViewHolder(BaseViewHolder holder, int position) {
        holder.itemView.setId(position);
        if (headers.size() != 0 && position < headers.size()) {
            headers.get(position).onBindView(holder.itemView);
            return;
        }

        int i = position - headers.size() - mDataList.size();
        if (footers.size() != 0 && i >= 0) {
            footers.get(i).onBindView(holder.itemView);
            return;
        }
        holder.onBindData(getDateItem(position - headers.size()));
    }


    @Deprecated
    @Override
    public final int getItemViewType(int position) {
        if (headers.size() > 0) {
            if (position < headers.size()) return headers.get(position).hashCode();
        }
        if (footers.size() > 0) {
            /*
            eg:
            0:header1
            1:header2   2
            2:object1
            3:object2
            4:object3
            5:object4
            6:footer1   6(position) - 2 - 4 = 0
            7:footer2
             */
            int i = position - headers.size() - mDataList.size();
            if (i >= 0) {
                return footers.get(i).hashCode();
            }
        }
        final BaseTemplate template = getTemplateByData(getDateItem(position - headers.size()));
        return template != null ? template.getViewType() : PlaceholderTemplate.sViewType;
    }

    /**
     * 根据数据获得模板对象
     *
     * @param data 数据
     * @return 模板对象
     */
    private BaseTemplate<?, ?> getTemplateByData(Object data) {
        if (data == null) {
            return null;
        }
        final Object key;
        if (data instanceof IAdapterData) {
            key = ((IAdapterData) data).getDataType();
        } else {
            key = data.getClass();
        }
        return mDataTypeTemplateMap.get(key);
    }


    public List<Object> getAllData() {
        return new ArrayList<>(mDataList);
    }

    /**
     * {@inheritDoc}
     */
    public Object getDateItem(int position) {
        return mDataList.get(position);
    }

    /**
     * Returns the position of the specified item in the array.
     *
     * @param item The item to retrieve the position of.
     * @return The position of the specified item.
     */
    public int getPosition(Object item) {
        return mDataList.indexOf(item);
    }

    /**
     * {@inheritDoc}
     */
    public long getItemId(int position) {
        return position;
    }

    private static void log(String content) {
        if (EasyRecyclerView.DEBUG) {
            Log.i(EasyRecyclerView.TAG, content);
        }
    }
}
